#-*-coding:UTF-8-*-

__author__='zhaoxp'

import collections

from random import choice
from math import hypot

Card = collections.namedtuple('Card', ['rank', 'suit'])

class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('jqka')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]
    
    def __len__(self):
        return len(self._cards)

    def __getitem__(self, position):
        return self._cards[position]

def show_usage1():
    print('usage of collections.namedtuple')
    beer_card = Card('7', 'diamonds')
    print('beer_card = %s'%str(beer_card))
    deck = FrenchDeck()
    print('len(deck) = %s'%len(deck))
    print('deck[0] = %s'%str(deck[0]))
    print('deck[-1] = %s'%str(deck[-1]))
    print('choice(deck) = %s'%str(choice(deck)))
    print('choice(deck) = %s'%str(choice(deck)))
    print('choice(deck) = %s'%str(choice(deck)))
    print('deck[:3] = %s'%deck[:3])
    print('deck[12::13] = %s'%deck[12::13])
    print('for in deck:')
    for card in deck:
        print(card)
    print('for in deck rrversed:')
    for card in reversed(deck):
        print(card)
    if Card('q', 'hearts') in deck:
        print("Card('q', 'hearts') in deck = True")
    else:
        print("Card('q', 'hearts') in deck = False")
    if Card('5', 'apple') in deck:
        print("Card('5', 'apple') in deck = True")
    else:
        print("Card('5', 'apple') in deck = False")


class Vector:
    
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return 'Vector(%r, %r)' % (self.x, self.y)

    def __abs__(self):
        return hypot(self.x, self.y)

    def __bool__(self):
        return bool(abs(self))

    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Vector(x, y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)


def show_usage2():
    print('\nusage of Vector')
    v1 = Vector(1, 1)
    v2 = Vector(3, 4)
    print('v1 = %s'%v1)
    print('v2 = %s'%v2)
    print('abs(v1) = %s'%abs(v1))
    print('abs(v2) = %s'%abs(v2))
    print('bool(v1) = %s'%bool(v1))
    print('bool(v2) = %s'%bool(v2))
    print('v1 + v2 = %s'%(v1+v2))
    print('v2 * 3 = %s'%(v2*3))

if __name__=='__main__':
    print('chapter 1 data model')
    show_usage1()
    show_usage2()